/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.platformservice.persistence.base;

import org.proteusframework.core.api.IPlatformDelegate;
import org.proteusframework.core.util.Assert;
import org.proteusframework.platformservice.IExtendedPlatformDelegate;
import org.proteusframework.platformservice.ServiceInitializationException;
import org.proteusframework.platformservice.appconfig.IAppConfigService;
import org.proteusframework.platformservice.persistence.api.IProjectDescriptor;
import org.proteusframework.platformservice.persistence.api.IProjectManager;
import org.proteusframework.platformservice.persistence.project.ProjectDescriptor;
import org.proteusframework.platformservice.persistence.project.ProjectProperty;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Properties;

public abstract class AbstractProjectManager implements IProjectManager
{
    private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    private IProjectDescriptor currentProjectDescriptor = null;

    /**
     * Injected platform delegate used to access platform services, including locating and instantiating other
     * Proteus objects.
     */
    private IExtendedPlatformDelegate delegate = null;

    private IAppConfigService appCfg;

    /**
     * {@inheritDoc}
     */
    @Override
    public final <T extends IPlatformDelegate> void setPlatformDelegate(final IPlatformDelegate delegate,
                                                                        Class<T> delegateInterface)
    {
        Assert.unitialized(this.delegate, "Application platform delegate is implicitly final and cannot be modified.");
        Assert.parameterNotNull(delegate, "Parameter 'delegate' must not be null");

        IExtendedPlatformDelegate extendedDelegate = delegate.adapt(IExtendedPlatformDelegate.class);
        appCfg = extendedDelegate.getAppConfigService();

        this.delegate = delegate.adapt(IExtendedPlatformDelegate.class);

        onDelegateInjected();
    }

    protected void onDelegateInjected()
    {

    }

    protected IExtendedPlatformDelegate getDelegate()
    {
        return delegate.adapt(IExtendedPlatformDelegate.class);
    }

    protected IAppConfigService getAppConfigService()
    {
        return appCfg;
    }

    @Override
    public boolean supportsProjectManagement()
    {
        return true;
    }

    @Override
    public final void addPropertyChangeListener(PropertyChangeListener projectPropertiesListener)
    {
        Assert.parameterNotNull(projectPropertiesListener, "Parameter 'projectPropertiesListener' must not be null");
        propertyChangeSupport.addPropertyChangeListener(projectPropertiesListener);
    }

    @Override
    public final void removePropertyChangeListener(PropertyChangeListener projectPropertiesListener)
    {
        propertyChangeSupport.removePropertyChangeListener(projectPropertiesListener);
    }

    @Override
    public final void setCurrentProjectDescription(String description)
    {
        if (isProjectOpen())
        {
            currentProjectDescriptor.setDescription(description);
        } else
        {
            throw new IllegalStateException("No project is currently opened");
        }
    }

    @Override
    public void setCurrentProjectProperty(String propertyGroup, String key, String value)
    {
        String oldValue = currentProjectDescriptor.getProperty(propertyGroup, key);


        Properties p = currentProjectDescriptor.getProperties(propertyGroup);
        if (null == p)
        {
            p = new Properties();
            p.setProperty(key, value);
            currentProjectDescriptor.getPropertiesMap().put(propertyGroup, p);
        } else
        {
            p.setProperty(key, value);
        }

        PropertyChangeEvent event = new PropertyChangeEvent(
                new ProjectProperty(currentProjectDescriptor, propertyGroup),
                key,
                oldValue,
                value);

        propertyChangeSupport.firePropertyChange(event);
    }

    @Override
    public IProjectDescriptor getCurrentProject()
    {
        return ProjectDescriptor.cloneReadOnlyDescriptor(currentProjectDescriptor);
    }

    /**
     * Provides access to the <i>actual</i> project descriptor, unlike the public {@link #getCurrentProject()} which
     * returns a <code>ProjectDescriptor.cloneReadOnlyDescriptor()</code> instance.
     *
     * @return actual mutable project descriptor
     */
    protected IProjectDescriptor getOpenProject()
    {
        return currentProjectDescriptor;
    }

    protected void closeOpenProject()
    {
        currentProjectDescriptor = null;
    }

    protected void projectRegistration(IProjectDescriptor descriptor) throws ServiceInitializationException
    {
        Assert.parameterNotNull(descriptor, "Parameter 'descriptor' must not be null");
        currentProjectDescriptor = descriptor;
    }

}
